// 贪吃蛇游戏逻辑

// 游戏状态变量
let canvas, ctx;
let snake = [];
let food = {};
let direction = '';
let nextDirection = '';
let score = 0;
let snakeLength = 1;
let gameInterval;
let isGameRunning = false;
let startTime;
let elapsedTime = 0;
let timerInterval;
let gameDuration;

// 游戏配置
const GRID_SIZE = 20;
const INITIAL_SPEED = 150; // 初始速度（毫秒）

// 页面加载完成后初始化游戏
window.addEventListener('DOMContentLoaded', function() {
    initializeGame();
});

// 初始化游戏
function initializeGame() {
    // 获取画布和上下文
    canvas = document.getElementById('snakeCanvas');
    ctx = canvas.getContext('2d');
    
    // 获取游戏设置
    const settings = getGameSettings();
    gameDuration = settings.gameDuration;
    
    // 显示最高分
    document.getElementById('highScore').textContent = getHighScore('snake');
    
    // 初始化蛇
    resetSnake();
    
    // 生成食物
    generateFood();
    
    // 绘制初始游戏状态
    draw();
    
    // 添加事件监听器
    document.getElementById('startBtn').addEventListener('click', startGame);
    document.getElementById('pauseBtn').addEventListener('click', togglePause);
    document.getElementById('resetBtn').addEventListener('click', resetGame);
    
    // 添加键盘控制
    document.addEventListener('keydown', handleKeyPress);
}

// 重置蛇的状态
function resetSnake() {
    const centerX = Math.floor(canvas.width / 2 / GRID_SIZE) * GRID_SIZE;
    const centerY = Math.floor(canvas.height / 2 / GRID_SIZE) * GRID_SIZE;
    
    snake = [
        { x: centerX, y: centerY }
    ];
    
    direction = 'right';
    nextDirection = 'right';
    score = 0;
    snakeLength = 1;
    elapsedTime = 0;
    
    // 更新显示
    document.getElementById('score').textContent = score;
    document.getElementById('snakeLength').textContent = snakeLength;
    document.getElementById('timer').textContent = formatTime(elapsedTime);
}

// 生成食物
function generateFood() {
    // 确保食物不会出现在蛇身上
    let newFood;
    let onSnake;
    
    do {
        onSnake = false;
        newFood = {
            x: Math.floor(Math.random() * (canvas.width / GRID_SIZE)) * GRID_SIZE,
            y: Math.floor(Math.random() * (canvas.height / GRID_SIZE)) * GRID_SIZE
        };
        
        // 检查是否与蛇重叠
        for (let segment of snake) {
            if (segment.x === newFood.x && segment.y === newFood.y) {
                onSnake = true;
                break;
            }
        }
    } while (onSnake);
    
    food = newFood;
}

// 开始游戏
function startGame() {
    if (isGameRunning) return;
    
    isGameRunning = true;
    startTime = Date.now() - elapsedTime * 1000;
    
    // 更新按钮状态
    document.getElementById('startBtn').disabled = true;
    document.getElementById('pauseBtn').disabled = false;
    
    // 启动游戏循环
    gameInterval = setInterval(gameLoop, calculateSpeed());
    
    // 启动计时器
    timerInterval = setInterval(updateTimer, 1000);
}

// 游戏主循环
function gameLoop() {
    // 更新方向
    updateDirection();
    
    // 移动蛇
    moveSnake();
    
    // 检查碰撞
    if (checkCollision()) {
        gameOver();
        return;
    }
    
    // 检查是否吃到食物
    if (checkFoodCollision()) {
        handleFoodEaten();
    }
    
    // 绘制游戏
    draw();
}

// 更新方向
function updateDirection() {
    // 防止180度转向（例如从向右直接变为向左）
    if ((nextDirection === 'up' && direction !== 'down') ||
        (nextDirection === 'down' && direction !== 'up') ||
        (nextDirection === 'left' && direction !== 'right') ||
        (nextDirection === 'right' && direction !== 'left')) {
        direction = nextDirection;
    }
}

// 移动蛇
function moveSnake() {
    // 获取蛇头位置
    const head = { x: snake[0].x, y: snake[0].y };
    
    // 根据方向移动蛇头
    switch (direction) {
        case 'up':
            head.y -= GRID_SIZE;
            break;
        case 'down':
            head.y += GRID_SIZE;
            break;
        case 'left':
            head.x -= GRID_SIZE;
            break;
        case 'right':
            head.x += GRID_SIZE;
            break;
    }
    
    // 添加新的头部
    snake.unshift(head);
    
    // 如果蛇没有吃到食物，移除尾部
    if (snake.length > snakeLength) {
        snake.pop();
    }
}

// 检查碰撞（墙壁或自身）
function checkCollision() {
    const head = snake[0];
    
    // 检查墙壁碰撞
    if (head.x < 0 || head.x >= canvas.width || 
        head.y < 0 || head.y >= canvas.height) {
        return true;
    }
    
    // 检查自身碰撞
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            return true;
        }
    }
    
    return false;
}

// 检查是否吃到食物
function checkFoodCollision() {
    return snake[0].x === food.x && snake[0].y === food.y;
}

// 处理吃到食物的情况
function handleFoodEaten() {
    // 增加分数和长度
    score += 10;
    snakeLength++;
    
    // 更新显示
    document.getElementById('score').textContent = score;
    document.getElementById('snakeLength').textContent = snakeLength;
    
    // 生成新食物
    generateFood();
    
    // 加快游戏速度
    clearInterval(gameInterval);
    gameInterval = setInterval(gameLoop, calculateSpeed());
}

// 计算游戏速度（随着分数增加而加快）
function calculateSpeed() {
    const speedDecrease = Math.min(score * 2, 80); // 最多减少80毫秒
    return INITIAL_SPEED - speedDecrease;
}

// 更新计时器
function updateTimer() {
    elapsedTime = Math.floor((Date.now() - startTime) / 1000);
    document.getElementById('timer').textContent = formatTime(elapsedTime);
    
    // 检查游戏时间是否结束
    if (gameDuration > 0 && elapsedTime >= gameDuration) {
        gameOver();
    }
}

// 绘制游戏
function draw() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制蛇
    snake.forEach((segment, index) => {
        // 蛇头使用不同颜色
        if (index === 0) {
            ctx.fillStyle = '#4CAF50';
        } else {
            ctx.fillStyle = '#8BC34A';
        }
        
        ctx.fillRect(segment.x, segment.y, GRID_SIZE, GRID_SIZE);
        
        // 添加边框
        ctx.strokeStyle = '#333';
        ctx.strokeRect(segment.x, segment.y, GRID_SIZE, GRID_SIZE);
    });
    
    // 绘制食物
    ctx.fillStyle = '#F44336';
    ctx.fillRect(food.x, food.y, GRID_SIZE, GRID_SIZE);
    ctx.strokeStyle = '#333';
    ctx.strokeRect(food.x, food.y, GRID_SIZE, GRID_SIZE);
}

// 切换暂停状态
function togglePause() {
    if (isGameRunning) {
        pauseGame();
    } else {
        resumeGame();
    }
}

// 暂停游戏
function pauseGame() {
    clearInterval(gameInterval);
    clearInterval(timerInterval);
    isGameRunning = false;
    document.getElementById('pauseBtn').textContent = '继续';
}

// 继续游戏
function resumeGame() {
    startTime = Date.now() - elapsedTime * 1000;
    gameInterval = setInterval(gameLoop, calculateSpeed());
    timerInterval = setInterval(updateTimer, 1000);
    isGameRunning = true;
    document.getElementById('pauseBtn').textContent = '暂停';
}

// 游戏结束
function gameOver() {
    // 停止游戏循环和计时器
    clearInterval(gameInterval);
    clearInterval(timerInterval);
    isGameRunning = false;
    
    // 更新按钮状态
    document.getElementById('startBtn').disabled = false;
    document.getElementById('pauseBtn').disabled = true;
    document.getElementById('pauseBtn').textContent = '暂停';
    
    // 记录分数
    recordScore('snake', score, elapsedTime);
    
    // 更新最高分
    document.getElementById('highScore').textContent = getHighScore('snake');
    
    // 显示游戏结束消息
    showMessage(`游戏结束！得分：${score}，用时：${formatTime(elapsedTime)}`, 'warning');
}

// 重置游戏
function resetGame() {
    // 停止游戏循环和计时器
    clearInterval(gameInterval);
    clearInterval(timerInterval);
    isGameRunning = false;
    
    // 更新按钮状态
    document.getElementById('startBtn').disabled = false;
    document.getElementById('pauseBtn').disabled = true;
    document.getElementById('pauseBtn').textContent = '暂停';
    
    // 重置蛇和分数
    resetSnake();
    
    // 生成新食物
    generateFood();
    
    // 重新绘制
    draw();
}

// 处理键盘输入
function handleKeyPress(e) {
    // 防止页面滚动
    if ([37, 38, 39, 40, 32].includes(e.keyCode)) {
        e.preventDefault();
    }
    
    switch (e.keyCode) {
        case 38: // 上箭头
        case 87: // W键
            nextDirection = 'up';
            break;
        case 40: // 下箭头
        case 83: // S键
            nextDirection = 'down';
            break;
        case 37: // 左箭头
        case 65: // A键
            nextDirection = 'left';
            break;
        case 39: // 右箭头
        case 68: // D键
            nextDirection = 'right';
            break;
        case 32: // 空格键
            if (isGameRunning) {
                togglePause();
            } else {
                startGame();
            }
            break;
        case 82: // R键
            resetGame();
            break;
    }
}